// router.js
import {
  RouterMount,
  createRouter
} from 'uni-simple-router'
import Vue from 'vue'
import store from '@/store'
import utils from '@/utils'
import ajax from '@/plugins/ajax'
import { APPID } from '@/env.js'

import pagesJson from '@/pages.json'

const { tabBar } = pagesJson

const tabBarList = tabBar.list.map(v => `/${v.pagePath}`)

const isTabbarPath = (path = '') => {
  return tabBarList.includes(path)
}

const router = createRouter({
  platform: process.env.VUE_APP_PLATFORM,
  routes: [...ROUTES]
})
// 全局路由前置守卫
router.beforeEach(async(to, from, next) => {
  if (utils.isH5()) {
    if (store.state.mountStatus === 0) {
      let mountStatus = isTabbarPath(to.path) ? 1 : 2
      store.commit('setState', { mountStatus })
    } else if (store.state.mountStatus === 2 && isTabbarPath(to.path)) {
      store.commit('setState', { mountStatus: 1 })
      window.location.href = location.href.split('#')[0] + '#' + (to.path === '/pages/index/index' ? '/' : to.path)
      return next(false)
    }
  }
  next()
  // if (utils.isH5Dev()) {
  //   utils.storeToken('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJqd3RfeWgiLCJleHAiOjE3MDg3NjU4MTEsInN1YiI6IllIIiwiYXVkIjoiZXZlcnkiLCJuYmYiOjE2NzcyMjk4MTEsImlhdCI6MTY3NzIyOTgxMSwianRpIjoxMDAwMSwidWlkIjoiZnJvbnQxODYifQ.qcU6FleP6ImZmxh1sE2tAW288LK7dH0oV6U_XHS4koU')
  // }
  // if (utils.isWx()) {
  //   let locHref = window.location.href
  //   let token = utils.cache('token')
  //   let redirectState = utils.getUrlParam('state')
  //   let code = utils.getUrlParam('code')
  //   if (redirectState && redirectState === utils.cache('wxRedirectState')) {
  //     utils.cache('wxRedirectState', null)
  //     let	fc = utils.getUrlParam('fc')
  //     let [authErr, authRes] = await utils.awaitTo(ajax.post)('app/wxAuth', { type: 0, code, fc })
  //     if (authErr) {
  //       let errNum = utils.cache('errNum') || 0
  //       if (errNum > 1) {
  //         alert(authErr.msg || authErr.data || '授权失败,请联系技术人员')
  //       } else {
  //         utils.cache('errNum', errNum + 1)
  //         let reUri = utils.delUrlParam(locHref.split('#')[0], ['code', 'state', 'reduri'])
  //         setTimeout(() => {
  //           window.location.href = reUri
  //         }, 500)
  //       }
  //       return next(false)
  //     } else {
  //       utils.storeToken(authRes.data.token)
  //     }
  //   } else if (!token) {
  //     if (code && !utils.cache('wxRedirectState')) {
  //       let [snapshotErr, snapshotRes] = await utils.awaitTo(ajax.post)('app/wxAuth', { code })
  //       if (!snapshotErr && snapshotRes.data.is_snapshotuser) {
  //         uni.clearStorageSync()
  //         utils.storeToken(snapshotRes.data.token)
  //         store.commit('setState', { isSnapshotuser: 1 })
  //         return next()
  //       }
  //     }
  //     // 第一次进入项目
  //     let scope = 'snsapi_userinfo' // snsapi_userinfo=高级授权； snsapi_base=静默授权
  //     let wxRedirectState = utils.randomStr(4)
  //     utils.cache('wxRedirectState', wxRedirectState)
  //     let redirectUri = utils.delUrlParam(locHref, ['code', 'state', 'reduri'])
  //     // 平台用的是公共域名，无需跳转APP_HOST下授权
  //     let authorUrl =
  // 			`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${APPID}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=code&forcePopup=true&forceSnapShot=true&scope=${scope}&state=${wxRedirectState}#wechat_redirect`
  //     // 重定向到微信授权
  //     window.location.replace(authorUrl)
  //     return next(false)
  //   } else if (store.state.mountStatus === 0) {
  //     let mountStatus = isTabbarPath(to.path) ? 1 : 2
  //     store.commit('setState', { mountStatus })
  //   } else if (store.state.mountStatus === 2 && isTabbarPath(to.path)) {
  //     store.commit('setState', { mountStatus: 1 })
  //     window.location.href = location.href.split('#')[0] + '#' + (to.path === '/pages/index/index' ? '/' : to.path)
  //     return next(false)
  //   }
  //   if (store.state.config.name && store.state.config.name !== document.title) {
  //     window.__uniConfig.globalStyle.navigationBarTitleText = store.state.config.name
  //     utils.setTitle(store.state.config.name)
  //   }
  // }
})
// 全局路由后置守卫
router.afterEach(async(to, from) => {
  const timer = setInterval(function() {
    if (!utils.isEmpty(store.state.config) && store.state.userInfo.id) {
      const { share_title, share_desc, share_logo } = store.state.config
      utils.wxShare({
        title: share_title,
        desc: share_desc,
        imgUrl: share_logo
      })
      clearInterval(timer)
    }
  }, 500)
})

export {
  router,
  RouterMount
}
